import React, { useState, useEffect } from 'react';
import axios from 'axios';
import {
    Card,
    Table,
    Button,
    Space,
    Tag,
    Typography,
    Row,
    Col,
    Statistic,
    DatePicker,
    Select,
    Input,
    message,
    Avatar,
    Tooltip,
    Badge,
    Popconfirm
} from 'antd';
import {
    BarChartOutlined,
    ReloadOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    UserOutlined,
    CalendarOutlined,
    ExportOutlined,
    DeleteOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

import { useWebSocket } from '../../contexts/WebSocketContext'; // 导入useWebSocket
import { getFullMediaUrl } from '../../utils/config'; // 导入URL构建函数

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { Search } = Input;

// 访问日志数据接口 (与WebSocketContext中定义一致)
interface AccessLog {
    id: number;
    user: string;
    user_avatar: string | null;
    device: string;
    device_id: string;
    timestamp: string;
    is_success: boolean;
    snapshot_path: string;
}

// 访问统计数据接口
interface AccessStats {
    total_today: number;
    success_today: number;
    failed_today: number;
    success_rate: number;
}

const AccessLogManagement: React.FC = () => {
    // 从WebSocket Context获取原始日志数据和操作方法
    const { logs: rawLogs, isConnected, removeLogById } = useWebSocket();
    const [displayLogs, setDisplayLogs] = useState<AccessLog[]>([]);

    const [stats, setStats] = useState<AccessStats>({
        total_today: 0,
        success_today: 0,
        failed_today: 0,
        success_rate: 0
    });
    const [searchText, setSearchText] = useState('');
    const [statusFilter, setStatusFilter] = useState<string>('all');
    const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

    // 处理日期范围变化
    const handleDateRangeChange = (dates: [dayjs.Dayjs | null, dayjs.Dayjs | null] | null) => {
        if (dates && dates[0] && dates[1]) {
            setDateRange([dates[0], dates[1]]);
        } else {
            setDateRange(null);
        }
    };

    // 在每次渲染时即时计算过滤后的日志
    const filteredLogs = React.useMemo(() => {
        let tempLogs = displayLogs;

        // 文本搜索
        if (searchText) {
            tempLogs = tempLogs.filter(log =>
                log.user.toLowerCase().includes(searchText.toLowerCase()) ||
                log.device.toLowerCase().includes(searchText.toLowerCase())
            );
        }

        // 状态筛选
        if (statusFilter !== 'all') {
            const isSuccess = statusFilter === 'success';
            tempLogs = tempLogs.filter(log => log.is_success === isSuccess);
        }

        // 日期范围筛选
        if (dateRange) {
            const [start, end] = dateRange;
            tempLogs = tempLogs.filter(log =>
                dayjs(log.timestamp).isAfter(start) && dayjs(log.timestamp).isBefore(end)
            );
        }

        return tempLogs;
    }, [displayLogs, searchText, statusFilter, dateRange]);

    // 当原始日志变化时，同步到本地状态并重新计算统计数据
    useEffect(() => {
        setDisplayLogs(rawLogs);

        const todayStart = dayjs().startOf('day');
        const todayLogs = rawLogs.filter(log => dayjs(log.timestamp).isAfter(todayStart));
        const successToday = todayLogs.filter(log => log.is_success).length;
        const failedToday = todayLogs.length - successToday;
        const successRate = todayLogs.length > 0 ? (successToday / todayLogs.length) * 100 : 0;

        setStats({
            total_today: todayLogs.length,
            success_today: successToday,
            failed_today: failedToday,
            success_rate: successRate,
        });
    }, [rawLogs]);


    // 获取状态标签
    const getStatusTag = (isSuccess: boolean, failureReason?: string) => {
        if (isSuccess) {
            return <Tag color="success" icon={<CheckCircleOutlined />}>成功</Tag>;
        } else {
            return (
                <Tooltip title={failureReason || '访问失败'}>
                    <Tag color="error" icon={<CloseCircleOutlined />}>失败</Tag>
                </Tooltip>
            );
        }
    };

    // 导出日志数据
    const handleExport = () => {
        // 模拟导出功能
        message.success('日志导出功能开发中...');
    };

    // 处理单条删除
    const handleDelete = async (id: number) => {
        try {
            const token = localStorage.getItem('adminAuthToken');
            await axios.delete(`/api/admin/logs/${id}/`, {
                headers: { Authorization: `Token ${token}` },
            });
            message.success(`成功删除日志 #${id}`);
            // 从全局Context中移除该日志
            removeLogById(id);
        } catch (error) {
            message.error('删除失败，请重试');
            console.error('Failed to delete log:', error);
        }
    };

    // 处理批量删除
    const handleBatchDelete = async () => {
        try {
            const token = localStorage.getItem('adminAuthToken');
            await axios.post('/api/admin/logs/batch-delete/', {
                ids: selectedRowKeys,
            }, {
                headers: { Authorization: `Token ${token}` },
            });
            message.success(`成功删除 ${selectedRowKeys.length} 条日志`);
            // 批量从全局Context中移除日志
            selectedRowKeys.forEach(id => removeLogById(id as number));
            setSelectedRowKeys([]);
        } catch (error) {
            message.error('批量删除失败，请重试');
            console.error('Failed to batch delete logs:', error);
        }
    };

    // 表格列定义
    const columns: ColumnsType<AccessLog> = [
        {
            title: '时间',
            dataIndex: 'timestamp',
            key: 'timestamp',
            width: 180,
            render: (timestamp) => (
                <div>
                    <div>{dayjs(timestamp).format('YYYY-MM-DD')}</div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                        {dayjs(timestamp).format('HH:mm:ss')}
                    </Text>
                </div>
            ),
            sorter: (a, b) => dayjs(a.timestamp).unix() - dayjs(b.timestamp).unix(),
            defaultSortOrder: 'descend',
        },
        {
            title: '用户',
            dataIndex: 'user',
            key: 'user',
            render: (user, record) => (
                <Space>
                    <Avatar
                        size="small"
                        src={getFullMediaUrl(record.user_avatar)}
                        icon={!record.user_avatar ? <UserOutlined /> : undefined}
                    />
                    <span>{user}</span>
                </Space>
            ),
        },
        {
            title: '设备',
            dataIndex: 'device',
            key: 'device',
            render: (device, record) => (
                <div>
                    <div>{device}</div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                        {record.device_id}
                    </Text>
                </div>
            ),
        },
        {
            title: '状态',
            dataIndex: 'is_success',
            key: 'is_success',
            render: (isSuccess) => getStatusTag(isSuccess),
        },
        {
            title: '操作',
            key: 'action',
            width: 100,
            render: (_, record) => (
                <Popconfirm
                    title={`确定要删除这条记录吗？`}
                    onConfirm={() => handleDelete(record.id)}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button type="link" danger>
                        删除
                    </Button>
                </Popconfirm>
            ),
        },
    ];

    const rowSelection = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys: React.Key[]) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
    };

    const hasSelected = selectedRowKeys.length > 0;

    return (
        <div style={{ padding: '24px' }}>
            <div style={{ marginBottom: '24px' }}>
                <Title level={2}>
                    <BarChartOutlined /> 访问日志
                </Title>
                <Text type="secondary">
                    查看和分析所有门禁访问记录
                </Text>
            </div>

            {/* 今日统计卡片 */}
            <Row gutter={16} style={{ marginBottom: '24px' }}>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="今日访问"
                            value={stats.total_today}
                            prefix={<CalendarOutlined />}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="成功访问"
                            value={stats.success_today}
                            prefix={<Badge status="success" />}
                            valueStyle={{ color: '#3f8600' }}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="失败访问"
                            value={stats.failed_today}
                            prefix={<Badge status="error" />}
                            valueStyle={{ color: '#cf1322' }}
                        />
                    </Card>
                </Col>
                <Col span={6}>
                    <Card>
                        <Statistic
                            title="成功率"
                            value={stats.success_rate}
                            precision={1}
                            suffix="%"
                            prefix={<Badge status="processing" />}
                            valueStyle={{ color: stats.success_rate >= 90 ? '#3f8600' : '#faad14' }}
                        />
                    </Card>
                </Col>
            </Row>

            {/* 筛选和搜索 */}
            <Card
                style={{ marginBottom: '24px' }}
                title="筛选与操作"
                extra={
                    <Space>
                        {hasSelected && <Text type="secondary">{`已选择 ${selectedRowKeys.length} 条记录`}</Text>}
                        <Button
                            icon={<ReloadOutlined />}
                            onClick={() => { /* WebSocket会自动刷新，此按钮可用于强制请求或保留 */ }}
                            loading={!isConnected}
                        >
                            {isConnected ? '已连接' : '连接中...'}
                        </Button>
                        <Button
                            icon={<ExportOutlined />}
                            onClick={handleExport}
                        >
                            导出
                        </Button>
                        <Popconfirm
                            title={`确定要删除选中的 ${selectedRowKeys.length} 条记录吗？`}
                            onConfirm={handleBatchDelete}
                            okText="确定"
                            cancelText="取消"
                            disabled={!hasSelected}
                        >
                            <Button
                                type="primary"
                                danger
                                icon={<DeleteOutlined />}
                                disabled={!hasSelected}
                            >
                                批量删除
                            </Button>
                        </Popconfirm>
                    </Space>
                }
            >
                <Row gutter={16} align="middle">
                    <Col span={8}>
                        <Search
                            placeholder="搜索用户名或设备名"
                            allowClear
                            value={searchText}
                            onChange={(e) => setSearchText(e.target.value)}
                            style={{ width: '100%' }}
                        />
                    </Col>
                    <Col span={6}>
                        <Select
                            placeholder="访问状态"
                            value={statusFilter}
                            onChange={setStatusFilter}
                            style={{ width: '100%' }}
                        >
                            <Option value="all">全部状态</Option>
                            <Option value="success">成功</Option>
                            <Option value="failed">失败</Option>
                        </Select>
                    </Col>
                    <Col span={10}>
                        <RangePicker
                            value={dateRange}
                            onChange={handleDateRangeChange}
                            style={{ width: '100%' }}
                            placeholder={['开始日期', '结束日期']}
                        />
                    </Col>
                </Row>
            </Card>

            {/* 访问日志列表 */}
            <Card title="访问记录">
                {displayLogs.length === 0 && isConnected ? (
                    <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
                        <BarChartOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                        <div style={{ fontSize: '16px', marginBottom: '8px' }}>暂无访问记录</div>
                        <div style={{ fontSize: '14px' }}>
                            当有用户使用门禁系统时，访问记录将在这里显示
                        </div>
                    </div>
                ) : (
                    <Table
                        rowSelection={rowSelection}
                        columns={columns}
                        dataSource={filteredLogs}
                        rowKey="id"
                        loading={!isConnected}
                        pagination={{
                            pageSize: 20,
                            showSizeChanger: true,
                            showQuickJumper: true,
                            showTotal: (total) => `共 ${total} 条记录`,
                        }}
                        scroll={{ x: 800, y: 600 }}
                    />
                )}
            </Card>
        </div>
    );
};

export default AccessLogManagement;
